const mySqlutil = require('../utils/mysql_util');
const squel = require('squel');
const ProjectJson = require('../mongod/project_json');
const _ = require('lodash');


// 根据主关键字删除方案多余版本文件
const deleteVersion = mongoKey => new Promise((res, rej) => {
  ProjectJson.remove({ _id: mongoKey }, (err) => {
    if (err) rej(err);
    else res();
  });
});


/**
 * 通过方案或户型编码，获取最新json数据
 * @param designId
 */
exports.findDesignJson = designId => new Promise((res, rej) => {
  // const dataMap = {};
  const sql = squel.select().from('project_version').field(' * ')
    .where('version =?', squel.select().from('project_version')
      .field('max(version) as max')
      .where('designId=?', designId))
    .where('designId=?', designId)
    .toString();
  mySqlutil.execute(sql)
    .then((projectVersion) => {
      if (projectVersion && projectVersion[0]) {
        ProjectJson.find({ _id: projectVersion[0].mongo_key }, (err, projectJsonData) => {
          if (err) rej(err);
          else if (projectJsonData && projectJsonData[0]) { res(projectJsonData[0]._doc.projectData); } else { res(); }
          // res(dataMap);
        });
      } else { res(); }
    })
    .catch((err) => {
      if (err) rej(err);
    });
});

/**
 * 保存方案data数据（json字符串），保存到mongodb，同时维护最新50个版本记录
 * @param strDesignJson
 * @param designId
 * @param userId
 */
exports.saveDesignJson = (strDesignJson, designId, userId) =>
  new Promise((res, rej) => {
    // 查询获取最新版本编号
    let maxVersion;
    const sql = squel.select().from('project_version').field('max(version) as max')
      .where('designId=?', designId)
      .toString();
    mySqlutil.execute(sql)
      .then((result) => {
        if (result && result[0] && result[0].max) {
          maxVersion = result[0].max + 1;
        } else {
          maxVersion = 1;
        }
        const designjson = new ProjectJson();
        designjson.projectData = strDesignJson;
        designjson.projectVersion = maxVersion.toString();
        designjson.projectDesignId = designId;
        designjson.userId = userId;
        // 将方案json数据保存到mongodb，
        designjson.save((err, resultDesignJson) => {
          if (err) rej(err);
          else {
            const params = {};
            params.designId = designId;
            params.version = maxVersion;
            params.mongo_key = resultDesignJson._id.toString();
            // 保存新版本信息
            mySqlutil.execute(squel.insert().into('project_version').setFields(params).toString())
              .then((result) => {
                res(result);
              })
              .catch((insertErr) => {
                if (insertErr) rej(insertErr);
              });
          }
        });
      })
      .catch((err) => {
        if (err) rej(err);
      });
  });

